{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from utils import tokenize, load_curpus\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...\n",
      "Loading model from cache /var/folders/dy/xjy0y7v97js5x1bghby2fnkm0000gn/T/jieba.cache\n",
      "Loading model cost 0.901 seconds.\n",
      "Prefix dict has been built succesfully.\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "train_data = load_curpus(\"weibo2018/train.txt\")\n",
    "test_data = load_curpus(\"weibo2018/test.txt\")\n",
    "train_df = pd.DataFrame(train_data, columns=[\"content\", \"sentiment\"])\n",
    "test_df = pd.DataFrame(test_data, columns=[\"content\", \"sentiment\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "stopwords = []\n",
    "with open(\"stopwords.txt\", \"r\", encoding=\"utf8\") as f:\n",
    "    for w in f:\n",
    "        stopwords.append(w.strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 词袋模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<10500x1000 sparse matrix of type '<class 'numpy.int64'>'\n",
       "\twith 76762 stored elements in Compressed Sparse Row format>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "data_str = [\" \".join(content) for content, sentiment in train_data] + \\\n",
    "            [\" \".join(content) for content, sentiment in test_data]\n",
    "vectorizer = CountVectorizer(token_pattern='\\[?\\w+\\]?', stop_words=stopwords, max_features=1000)\n",
    "vectorizer.fit_transform(data_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "X_data, y_data = [], []\n",
    "for content, sentiment in train_data:\n",
    "    X, y = [], sentiment\n",
    "    X_data.append(\" \".join(content))\n",
    "    y_data.append(sentiment)\n",
    "X_train = vectorizer.transform(X_data)\n",
    "y_train = y_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "X_data, y_data = [], []\n",
    "for content, sentiment in test_data:\n",
    "    X, y = [], sentiment\n",
    "    X_data.append(\" \".join(content))\n",
    "    y_data.append(sentiment)\n",
    "X_test = vectorizer.transform(X_data)\n",
    "y_test = y_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### XGBoost"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from xgboost import XGBClassifier\n",
    "xgb = XGBClassifier(n_estimators=200,       # 200棵树\n",
    "                    max_depth=10,                         # 每棵树的最大深度为10\n",
    "                    subsample=0.7,                        # 样本下采样\n",
    "                    scale_pos_weight=0.5)             # 不平衡分类，适当降低正面情感权重有助于提升总体准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "XGBClassifier(base_score=0.5, booster=None, colsample_bylevel=1,\n",
       "       colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=-1,\n",
       "       importance_type='gain', interaction_constraints=None,\n",
       "       learning_rate=0.300000012, max_delta_step=0, max_depth=10,\n",
       "       min_child_weight=1, missing=nan, monotone_constraints=None,\n",
       "       n_estimators=200, n_jobs=0, num_parallel_tree=1,\n",
       "       objective='binary:logistic', random_state=0, reg_alpha=0,\n",
       "       reg_lambda=1, scale_pos_weight=0.5, subsample=0.7, tree_method=None,\n",
       "       validate_parameters=False, verbosity=None)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "xgb.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/dengxiuqi/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/label.py:151: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty.\n",
      "  if diff:\n"
     ]
    }
   ],
   "source": [
    "result=xgb.predict(X_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 模型评估\n",
    "XGBoost真是机器学习界的一大杀器，在这种简单任务上真是又快又好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "          0       0.76      0.86      0.81       155\n",
      "          1       0.93      0.88      0.91       345\n",
      "\n",
      "avg / total       0.88      0.87      0.88       500\n",
      "\n",
      "准确率: 0.874\n"
     ]
    }
   ],
   "source": [
    "from sklearn import metrics\n",
    "print(metrics.classification_report(y_test, result))\n",
    "print(\"准确率:\", metrics.accuracy_score(y_test, result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查看权重最高的“重要特征”\n",
    "越靠前，说明其越重要"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "features = vectorizer.get_feature_names()\n",
    "weights = xgb.feature_importances_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 :  [心]\n",
      "1 :  难受\n",
      "2 :  哈哈哈\n",
      "3 :  mmp\n",
      "4 :  同济大学\n",
      "5 :  呵呵\n",
      "6 :  [微笑]\n",
      "7 :  伤心\n",
      "8 :  恶心\n",
      "9 :  [doge]\n",
      "10 :  逼\n",
      "11 :  [哈哈]\n",
      "12 :  去死吧\n",
      "13 :  sb\n",
      "14 :  分手\n",
      "15 :  服\n",
      "16 :  cnmd\n",
      "17 :  [爱你]\n",
      "18 :  [摊手]\n",
      "19 :  [拜拜]\n",
      "20 :  心碎\n",
      "21 :  感谢\n",
      "22 :  婊\n",
      "23 :  完美\n",
      "24 :  哒\n",
      "25 :  骂\n",
      "26 :  diss\n",
      "27 :  不想\n",
      "28 :  无语\n",
      "29 :  委屈\n",
      "30 :  [兔子]\n",
      "31 :  [太开心]\n",
      "32 :  [笑而不语]\n",
      "33 :  哭哭\n",
      "34 :  哈哈\n",
      "35 :  [污]\n",
      "36 :  [泪]\n",
      "37 :  [怒]\n",
      "38 :  愿\n",
      "39 :  mlgb\n",
      "40 :  [嘻嘻]\n",
      "41 :  好看\n",
      "42 :  滚\n",
      "43 :  傻\n",
      "44 :  [喵喵]\n",
      "45 :  不行\n",
      "46 :  [失望]\n",
      "47 :  [偷笑]\n",
      "48 :  丧\n",
      "49 :  [憧憬]\n"
     ]
    }
   ],
   "source": [
    "for i, index in enumerate(weights.argsort()[::-1][:50]):\n",
    "    print(i, \": \", features[index])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
